//
//  DealsViewController.m
//  MeiTuan
//
//  Created by Ansen on 15-3-25.
//  Copyright (c) 2015年 Ansen. All rights reserved.
//

#import "DealsViewController.h"
#import "MJRefresh.h"
#import "DPAPI.h"
#import "DealCell.h"
#import "Const.h"
#import "UIView+AutoLayout.h"
#import "MJExtension.h"
#import "Deal.h"
#import "UIView+Extension.h"
#import "MBProgressHUD+MJ.h"
#import "DetailViewController.h"

@interface DealsViewController ()<DPRequestDelegate>

/** 所有的团购数据 */
@property (nonatomic ,strong) NSMutableArray *deals;
/** 记录当前页码 */
@property (nonatomic, assign) int currentPage;

/** 最后一个请求 */
@property (nonatomic, weak) DPRequest *lastRequest;

@property (nonatomic, weak) UIImageView *noDataView;

/** 总数 */
@property (nonatomic, assign) int  totalCount;

@end

@implementation DealsViewController

static NSString * const reuseIdentifier = @"deal";

-(NSMutableArray *)deals
{
    if (!_deals) {
        self.deals = [NSMutableArray array];
    }
    return _deals;
}

-(UIImageView *)noDataView
{
    if (!_noDataView) {
        // 添加一个"没有数据"的提醒
        UIImageView *noDataView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"icon_deals_empty"]];
        [self.view addSubview:noDataView];
        [noDataView autoCenterInSuperview];
        self.noDataView = noDataView;
    }
    return _noDataView;
}
-(instancetype)init
{
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    // cell的大小
    layout.itemSize = CGSizeMake(305, 305);
    return [self initWithCollectionViewLayout:layout];
}


- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.collectionView.backgroundColor = GlobalBg;
    [self.collectionView registerNib:[UINib nibWithNibName:@"DealCell" bundle:nil] forCellWithReuseIdentifier:reuseIdentifier];
    self.collectionView.alwaysBounceVertical = YES;
    
    // 添加上拉刷新
    [self.collectionView addFooterWithTarget:self action:@selector(loadMoreDeals)];
    [self.collectionView addHeaderWithTarget:self action:@selector(loadNewDeals)];
}

-(void)viewWillTransitionToSize:(CGSize)size withTransitionCoordinator:(id<UIViewControllerTransitionCoordinator>)coordinator
{
    // 根据屏幕宽度决定列数
    int cols = size.width == 1024 ? 3 : 2;
    
    // 根据列数计算内边距
    UICollectionViewFlowLayout *layout = (UICollectionViewFlowLayout *)self.collectionViewLayout;
    CGFloat inset = (size.width - cols * layout.itemSize.width)/(cols+1);
    layout.sectionInset = UIEdgeInsetsMake(inset, inset, inset, inset);
    // 设置每一行之间的间距
    layout.minimumLineSpacing = inset;
}

-(void)request:(DPRequest *)request didFinishLoadingWithResult:(id)result
{
    
    if (request != self.lastRequest) return;
    self.totalCount = [result[@"total_count"]intValue];
    
    // 1.取出团购的字典数组
    NSArray *newdeals = [Deal objectArrayWithKeyValuesArray:result[@"deals"]];
    if (self.currentPage == 1) {// 清除之前的旧数据
        [self.deals removeAllObjects];
    }
    [self.deals addObjectsFromArray:newdeals];
    
    // 2.刷新表格
    [self.collectionView reloadData];
    
    // 3.结束上拉加载 / 下拉
    [self.collectionView footerEndRefreshing];
    [self.collectionView headerEndRefreshing];
    
}

-(void)request:(DPRequest *)request didFailWithError:(NSError *)error
{
    // 1.提醒失败
    if (request != self.lastRequest) return;
    [MBProgressHUD showError:@"网络繁忙，请稍候再试"];
    
    // 2.结束刷新
    [self.collectionView headerEndRefreshing];
    [self.collectionView footerEndRefreshing];
    
    // 3.如果是上拉加载失败了
    if (self.currentPage > 1) {
        self.currentPage -- ;
    }
}


#pragma mark <UICollectionViewDataSource>

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    // 计算一遍内边距
    [self viewWillTransitionToSize:CGSizeMake(collectionView.width, 0) withTransitionCoordinator:nil];
    self.collectionView.footerHidden = (self.totalCount == self.deals.count);
    self.noDataView.hidden = (self.deals.count != 0);
    return 1;
}


- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return self.deals.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    DealCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:reuseIdentifier forIndexPath:indexPath];
    cell.deal = _deals[indexPath.row];
    
    
    return cell;
}
#pragma mark - 跟服务器交互

- (void)loadDeals
{
    DPAPI *api = [[DPAPI alloc] init];
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    [self setupParams:params];
    // 每页的条数
    params[@"limit"] = @10;
    // 页码
    params[@"page"] = @(self.currentPage);
    self.lastRequest = [api requestWithURL:@"v1/deal/find_deals" params:params delegate:self];
    
}

-(void)loadMoreDeals
{
    self.currentPage ++;
    [self loadDeals];
}

-(void)loadNewDeals
{
    self.currentPage = 1;
    [self loadDeals];
}

-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    DetailViewController *detail = [[DetailViewController alloc] init];
    detail.deal = self.deals[indexPath.row];
    [self presentViewController:detail animated:YES completion:nil];
    
}



@end
